import { parse as parseSvgString } from 'svg-parser';
import { SVGPathData } from "svg-pathdata";
import { v4 as uuidv4 } from 'uuid';

const parse_d = require("d-path-parser");

// DHand 处理方式 0 不处理 1 转成对象 2 canvas 命令

const parseSvg = (str, { viewBoxHand = false, DHand = 0 }) => {
    if (!str) return {}

    const SvgObj = parseSvgString(str)
    DHand !== 0 && (SvgObj.vis_commands = [])
    viewBoxHand && (SvgObj.vis_bounds = { minX: 0, maxX: 0, minY: 0, maxY: 0 })



    // 解析viewbox、path的d
    function hand(obj) {
        const keys = Object.keys(obj)

        if (keys.includes('properties')) {
            obj.properties.render_id = uuidv4()
            const propertiesKeys = Object.keys(obj.properties)
            if (viewBoxHand && propertiesKeys.includes('viewBox')) {
                const tempViewBox = obj.properties.viewBox
                const handRes = parseViewBox(tempViewBox)
                obj.properties.viewBox = handRes

                // 为可视化单独设置属性
                SvgObj.vis_bounds.minX = handRes[0]
                SvgObj.vis_bounds.minY = handRes[1]
                SvgObj.vis_bounds.maxX = handRes[2]
                SvgObj.vis_bounds.maxY = handRes[3]
            }

            if (DHand && propertiesKeys.includes('d')) {
                const tempD = obj.properties.d
                const handRes = DHand === 1 ? parsePathD(tempD) : new SVGPathData(tempD).commands
                obj.properties.d = handRes

                // 为可视化单独设置属性
                SvgObj.vis_commands = [...SvgObj.vis_commands, ...handRes]
            }
        }

        if (!keys.includes('children')) return

        obj.children.forEach((item) => hand(item))
    }


    hand(SvgObj)

    return SvgObj
}



function parseViewBox(str) {
    if (!str) return []
    return str.split(' ')
}


function parsePathD(str) {
    if (!str) return []
    return parse_d(str)
}

export default parseSvg



